package com.xq.tmall.controller.admin;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xq.tmall.controller.BaseController;
import com.xq.tmall.entity.Address;
import com.xq.tmall.entity.Product;
import com.xq.tmall.entity.ProductOrderItem;
import com.xq.tmall.entity.User;
import com.xq.tmall.service.*;
import com.xq.tmall.util.OrderUtil;
import com.xq.tmall.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 * 后台管理-用户页
 */
@Controller
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private ReviewService reviewService;
    @Autowired
    private ProductOrderItemService productOrderItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImageService productImageService;

    //转到后台管理-用户页-ajax
    @RequestMapping(value = "admin/user", method = RequestMethod.GET)
    public String goUserManagePage(HttpSession session, Map<String, Object> map) {
        logger.info("检查管理员权限");
        Object adminId = checkAdmin(session);
        if (adminId == null) {
            return "admin/include/loginMessage";
        }

        logger.info("获取前十条用户信息");
        PageUtil pageUtil = new PageUtil(0, 10);
        List<User> userList = userService.getList(null, null, pageUtil);
        map.put("userList", userList);
        logger.info("获取用户总数量");
        Integer userCount = userService.getTotal(null);
        map.put("userCount", userCount);
        logger.info("获取分页信息");
        pageUtil.setTotal(userCount);
        map.put("pageUtil", pageUtil);

        logger.info("转到后台管理-用户页-ajax方式");
        return "admin/userManagePage";
    }


    //转到后台管理-用户详情页-ajax
    @RequestMapping(value = "admin/user/{uid}", method = RequestMethod.GET)
    public String getUserById(HttpSession session, Map<String, Object> map, @PathVariable Integer uid/* 用户ID */) {
        logger.info("检查管理员权限");
        Object adminId = checkAdmin(session);
        if (adminId == null) {
            return "admin/include/loginMessage";
        }

        logger.info("获取user_id为{}的用户信息", uid);
        User user = userService.get(uid);
        logger.info("获取用户详情-所在地地址信息");
        Address address = addressService.get(user.getUser_address().getAddress_areaId());
        Stack<String> addressStack = new Stack<>();
        //最后一级地址
        addressStack.push(address.getAddress_name() + " ");
        //如果不是第一级地址
        while (!address.getAddress_areaId().equals(address.getAddress_regionId().getAddress_areaId())) {
            address = addressService.get(address.getAddress_regionId().getAddress_areaId());
            addressStack.push(address.getAddress_name() + " ");
        }
        StringBuilder builder = new StringBuilder();
        while (!addressStack.empty()) {
            builder.append(addressStack.pop());
        }
        logger.info("所在地地址字符串：{}", builder);
        user.setUser_address(new Address().setAddress_name(builder.toString()));

        logger.info("获取用户详情-家乡地址信息");
        address = addressService.get(user.getUser_homeplace().getAddress_areaId());
        //最后一级地址
        addressStack.push(address.getAddress_name() + " ");
        //如果不是第一级地址
        while (!address.getAddress_areaId().equals(address.getAddress_regionId().getAddress_areaId())) {
            address = addressService.get(address.getAddress_regionId().getAddress_areaId());
            addressStack.push(address.getAddress_name() + " ");
        }
        builder = new StringBuilder();
        while (!addressStack.empty()) {
            builder.append(addressStack.pop());
        }
        logger.info("家乡地址字符串：{}", builder);
        user.setUser_homeplace(new Address().setAddress_name(builder.toString()));

        logger.info("获取用户详情-购物车订单项信息");
        List<ProductOrderItem> productOrderItemList = productOrderItemService.getListByUserId(user.getUser_id(), null);
        if (productOrderItemList != null) {
            logger.info("获取用户详情-购物车订单项对应的产品信息");
            for (ProductOrderItem productOrderItem : productOrderItemList) {
                Integer productId = productOrderItem.getProductOrderItem_product().getProduct_id();
                logger.warn("获取产品ID为{}的产品信息", productId);
                Product product = productService.get(productId);
                if (product != null) {
                    logger.warn("获取产品ID为{}的第一张预览图片信息", productId);
                    product.setSingleProductImageList(productImageService.getList(productId, (byte) 0, new PageUtil(0, 1)));
                }
                productOrderItem.setProductOrderItem_product(product);
            }
        }
        user.setProductOrderItemList(productOrderItemList);

        if (!StringUtils.isEmpty(user.getUser_realname())) {
            logger.info("用户隐私加密");
            user.setUser_realname(user.getUser_realname().substring(0, 1) + "*");
        } else {
            user.setUser_realname("未命名");
        }

        map.put("user", user);

        logger.info("转到后台管理-用户详情页-ajax方式");
        return "admin/include/userDetails";
    }

    //按条件查询用户-ajax
    @ResponseBody
    @RequestMapping(value = "admin/user/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getUserBySearch(@RequestParam(required = false) String user_name/* 用户名称 */,
                                  @RequestParam(required = false) Byte[] user_gender_array/* 用户性别数组 */,
                                  @RequestParam(required = false) String orderBy/* 排序字段 */,
                                  @RequestParam(required = false, defaultValue = "true") Boolean isDesc/* 是否倒序 */,
                                  @PathVariable Integer index/* 页数 */,
                                  @PathVariable Integer count/* 行数 */) throws UnsupportedEncodingException {
        //移除不必要条件
        Byte gender = null;
        if (user_gender_array != null && user_gender_array.length == 1) {
            gender = user_gender_array[0];
        }

        if (user_name != null) {
            //如果为非空字符串则解决中文乱码：URLDecoder.decode(String,"UTF-8");
            user_name = "".equals(user_name) ? null : URLDecoder.decode(user_name, "UTF-8");
        }
        if (orderBy != null && "".equals(orderBy)) {
            orderBy = null;
        }
        //封装查询条件
        User user = new User()
                .setUser_name(user_name)
                .setUser_gender(gender);

        OrderUtil orderUtil = null;
        if (orderBy != null) {
            logger.info("根据{}排序，是否倒序:{}", orderBy, isDesc);
            orderUtil = new OrderUtil(orderBy, isDesc);
        }

        JSONObject object = new JSONObject();
        logger.info("按条件获取第{}页的{}条用户", index + 1, count);
        PageUtil pageUtil = new PageUtil(index, count);
        List<User> userList = userService.getList(user, orderUtil, pageUtil);
        object.put("userList", JSONArray.parseArray(JSON.toJSONString(userList)));
        logger.info("按条件获取用户总数量");
        Integer userCount = userService.getTotal(user);
        object.put("userCount", userCount);
        logger.info("获取分页信息");
        pageUtil.setTotal(userCount);
        object.put("totalPage", pageUtil.getTotalPage());
        object.put("pageUtil", pageUtil);

        return object.toJSONString();
    }
    
    //删除单个用户-ajax
    @ResponseBody
    @RequestMapping(value = "admin/user/delete/{user_id}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    public String deleteUser(HttpSession session, @PathVariable Integer user_id) {
        JSONObject object = new JSONObject();
        logger.info("检查管理员权限");
        Object adminId = checkAdmin(session);
        if (adminId == null) {
            object.put("success", false);
            object.put("message", "无管理员权限");
            return object.toJSONString();
        }
        
        logger.info("准备删除用户，用户ID: {}", user_id);
        User user = userService.get(user_id);
        if (user == null) {
            logger.warn("用户不存在，删除失败");
            object.put("success", false);
            object.put("message", "用户不存在");
            return object.toJSONString();
        }
        
        boolean isSuccess = userService.delete(user_id);
        if (isSuccess) {
            logger.info("删除用户成功");
            object.put("success", true);
            object.put("message", "删除成功");
        } else {
            logger.warn("删除用户失败");
            object.put("success", false);
            object.put("message", "删除失败");
        }
        
        return object.toJSONString();
    }
    
    //批量删除用户-ajax
    @ResponseBody
    @RequestMapping(value = "admin/user/delete/batch", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    public String deleteUsers(HttpSession session, @RequestParam(value = "user_id_list[]") Integer[] user_id_list) {
        JSONObject object = new JSONObject();
        logger.info("检查管理员权限");
        Object adminId = checkAdmin(session);
        if (adminId == null) {
            object.put("success", false);
            object.put("message", "无管理员权限");
            return object.toJSONString();
        }
        
        logger.info("准备批量删除用户，用户ID列表: {}", Arrays.toString(user_id_list));
        if (user_id_list == null || user_id_list.length == 0) {
            logger.warn("用户ID列表为空，删除失败");
            object.put("success", false);
            object.put("message", "请选择要删除的用户");
            return object.toJSONString();
        }
        
        int successCount = 0;
        for (Integer userId : user_id_list) {
            try {
                if (userService.delete(userId)) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("删除用户ID为" + userId + "的用户时出错", e);
            }
        }
        
        if (successCount == user_id_list.length) {
            logger.info("批量删除用户成功，共删除{}个用户", successCount);
            object.put("success", true);
            object.put("message", "成功删除" + successCount + "个用户");
        } else if (successCount > 0) {
            logger.warn("部分用户删除成功，成功{}个，失败{}个", successCount, user_id_list.length - successCount);
            object.put("success", true);
            object.put("message", "成功删除" + successCount + "个用户，" + (user_id_list.length - successCount) + "个用户删除失败");
        } else {
            logger.warn("批量删除用户失败");
            object.put("success", false);
            object.put("message", "删除失败");
        }
        
        return object.toJSONString();
    }



    //获取子级地址列表-ajax（参考前端地址控制器实现）
    @ResponseBody
    @RequestMapping(value = "admin/address/children/{parentId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getChildrenAddress(@PathVariable String parentId) {
        JSONObject object = new JSONObject();
        try {
            logger.info("获取父级地址ID为{}的子级地址列表", parentId);
            
            // 获取直接子级地址
            List<Address> addressList = addressService.getList(null, parentId);
            logger.info("查询到{}条直接子级地址", addressList != null ? addressList.size() : 0);
            
            // 如果有子级地址，再获取第一个子级地址的子级地址（用于三级联动）
            List<Address> childAddressList = null;
            if (addressList != null && !addressList.isEmpty()) {
                String firstChildId = addressList.get(0).getAddress_areaId();
                childAddressList = addressService.getList(null, firstChildId);
                logger.info("查询到{}条孙级地址", childAddressList != null ? childAddressList.size() : 0);
            }
            
            object.put("success", true);
            object.put("addressList", JSONArray.parseArray(JSON.toJSONString(addressList)));
            if (childAddressList != null && !childAddressList.isEmpty()) {
                object.put("childAddressList", JSONArray.parseArray(JSON.toJSONString(childAddressList)));
            } else {
                object.put("childAddressList", new JSONArray());
            }
            
            logger.info("成功返回地址数据");
        } catch (Exception e) {
            logger.error("获取子级地址列表时出错", e);
            object.put("success", false);
            object.put("message", "获取地址列表失败：" + e.getMessage());
        }
        return object.toJSONString();
    }

    //获取根级地址列表-ajax（用于调试）
    @ResponseBody
    @RequestMapping(value = "admin/address/root", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getRootAddress() {
        JSONObject object = new JSONObject();
        try {
            logger.info("获取根级地址列表");
            List<Address> rootList = addressService.getRoot();
            logger.info("查询到{}条根级地址", rootList != null ? rootList.size() : 0);
            
            if (rootList != null && !rootList.isEmpty()) {
                for (Address addr : rootList) {
                    logger.info("根级地址: {} - {}", addr.getAddress_areaId(), addr.getAddress_name());
                }
            }
            
            object.put("success", true);
            object.put("addressList", JSONArray.parseArray(JSON.toJSONString(rootList)));
        } catch (Exception e) {
            logger.error("获取根级地址列表时出错", e);
            object.put("success", false);
            object.put("message", "获取根级地址列表失败：" + e.getMessage());
        }
        return object.toJSONString();
    }

    //测试特定地址的子级地址
    @ResponseBody
    @RequestMapping(value = "admin/address/test/{parentId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String testAddress(@PathVariable String parentId) {
        JSONObject object = new JSONObject();
        try {
            logger.info("测试获取父级地址ID为{}的子级地址", parentId);
            
            // 先获取父级地址信息
            Address parentAddress = addressService.get(parentId);
            if (parentAddress != null) {
                logger.info("父级地址信息: {} - {}", parentAddress.getAddress_areaId(), parentAddress.getAddress_name());
            } else {
                logger.warn("未找到父级地址: {}", parentId);
            }
            
            // 获取子级地址
            List<Address> childrenList = addressService.getList(null, parentId);
            logger.info("查询到{}条子级地址", childrenList != null ? childrenList.size() : 0);
            
            if (childrenList != null && !childrenList.isEmpty()) {
                for (Address addr : childrenList) {
                    logger.info("子级地址: {} - {} (父级: {})", 
                        addr.getAddress_areaId(), 
                        addr.getAddress_name(), 
                        addr.getAddress_regionId() != null ? addr.getAddress_regionId().getAddress_areaId() : "null");
                }
                object.put("success", true);
                object.put("parentAddress", parentAddress);
                object.put("addressList", JSONArray.parseArray(JSON.toJSONString(childrenList)));
            } else {
                object.put("success", true);
                object.put("parentAddress", parentAddress);
                object.put("addressList", new JSONArray());
                object.put("message", "未找到子级地址");
            }
        } catch (Exception e) {
            logger.error("测试地址时出错", e);
            object.put("success", false);
            object.put("message", "测试失败：" + e.getMessage());
        }
        return object.toJSONString();
    }
}
